import {Cascader} from "antd";
import React from "react";
import BaseComponent from "../../../redare/components/BaseComponent";
import BaseAreaPresenter from "../../../.gen/presenter/BaseAreaPresenter";

export default class AreaCascader extends BaseComponent {


    constructor(props) {
        super(props);
        this.state = {
            options: [],
            defaultValue: [],
        };
        this.presenter = new BaseAreaPresenter(this);
    }

    componentDidMount() {
        this._loadAreaData();
    }

    _loadAreaData() {
        this.presenter.findAreaList({}, {},
            (result) => {
                let {data} = result;
                this.setState({options: data})
            })
    }

    _getAreaData() {
        return this.areaData;
    }

    _setAreaData(areaData) {
        if (areaData) {
            this.areaData = {
                "provinceCode": areaData.provinceCode,
                'province': areaData.province,
                "cityCode": areaData.cityCode,
                'city': areaData.city,
                'districtCode': areaData.districtCode,
                'district': areaData.district
            };
            let value = [areaData.provinceCode, areaData.cityCode];
            if (areaData.districtCode) {
                value.push(areaData.districtCode)
            }
            this.handleChange(value)
        }
    }

    _resetAreaData() {
        this.areaData = {};
        this.setState({newValue: null})
    }

    handleChange(value, options) {
        if (options && options.length > 0) {
            this.areaData = {
                "provinceCode": options[0].areaCode,
                'province': options[0].areaName,
            };
            if (options.length >1) {
                this.areaData.cityCode = options[1].areaCode;
                this.areaData.city = options[1].areaName;
            }
            if (options.length > 2) {
                this.areaData.districtCode = options[2].areaCode;
                this.areaData.district = options[2].areaName;
            }
        }
        if (this.props.onChange) {
            this.props.onChange(value)
        }
        this.setState({
            newValue: value
        });
    }

    render() {
        let {options, newValue} = this.state;
        return (
            <Cascader
                {...this.props}
                value={newValue}
                options={options}
                placeholder="请选择地区"
                showSearch={true}
                onChange={this.handleChange.bind(this)}
                fieldNames={{label: 'areaName', value: 'areaCode', children: 'children'}}
                getPopupContainer={
                    triggerNode => triggerNode.parentElement
                }
            />
        )
    }
}
